//
//  ScanPageViewController.swift
//  MTBLETools
//
//  Created by 方强 on 16/8/26.
//  Copyright © 2016年 MT. All rights reserved.
//

import UIKit
import SVPullToRefresh
import MTSDK

class ScanPageViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{

    private var mStaticDatas: StaticDatas!;
    override func viewDidLoad() {
        super.viewDidLoad()
        
        mStaticDatas = StaticDatas.getInstance();
        
        initView();
        
        reciveBroadcast();
        
        initBLE();
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return mStaticDatas.deviceList.count;
    }
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let obj: AnyObject? = tableView.dequeueReusableCell(withIdentifier: "DeviceCell");
        var cell: DeviceCell!;
        if(obj == nil){
            cell = DeviceCell.devicefmtCell();
        }else{
            cell = obj as! DeviceCell;
        }
            
        cell.refreshDis(value: mStaticDatas.deviceList[indexPath.row]);
            
        return cell;
    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        return 70;
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        tableView.deselectRow(at: indexPath, animated: true);
        
        let selectedDevice = mStaticDatas.deviceList[indexPath.row];
        
        if(!selectedDevice.isConnectAble()){
            showFailAlert(erromsg: "不允许连接，下拉刷新试试");
            return;
        }
        
        if(selectedDevice.getDevicetype() == MTBLEDevice_MTBLEDEVICETYPE.MTBeacon3){
            let vc = SetBeacon123ViewController.getActivity();
            
            vc.working_device = selectedDevice;
            vc.pwd = mStaticDatas.mixDatas.beaconPwd;
            
            self.present(vc, animated: false, completion: {
                
            });
            
            return;
        }
        
        if(selectedDevice.getDevicetype() == MTBLEDevice_MTBLEDEVICETYPE.MTBeacon4){
            let vc = SetBeacon4ViewController.getActivity();
            
            vc.working_device = selectedDevice;
            vc.pwd = "123456";
            
            self.present(vc, animated: false, completion: {
                
            });
            return;
        }
        
        if(selectedDevice.getDevicetype() == MTBLEDevice_MTBLEDEVICETYPE.MTBLE){
            
            let vc = MTSeriBleTalkViewController.getActivity();
            
            vc.working_device = selectedDevice;
            self.present(vc, animated: false, completion: { 
                
            });
            
            return;
        }
        
        showFailAlert(erromsg: "对不起，暂不支持此设备");
    }
    
    // 显示失败对话框
    private var baseAlert: UIAlertView!;
    private func showFailAlert(erromsg: String){
        baseAlert = UIAlertView(title: "Fail", message: erromsg, delegate: nil, cancelButtonTitle: "OK");
        baseAlert.show();
    }
    
    // 初始化控件
    @IBOutlet weak var tableView: UITableView!
    private func initView(){
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.addPullToRefresh {
            print("开始刷新");
            self.manager.stopScan();
            self.mStaticDatas.deviceList.removeAll();
            self.tableView.reloadData();
            self.manager.startScan(scanmode: MTBLEManager_ScanMode.FAST, serviceUuids: nil, scanCallback: self.scanCallback, worktime: 10, sleeptime: 1, scanTimes: 0);
            Timer.scheduledTimer(timeInterval: TimeInterval(1), target: self, selector: #selector(self.pullRefresh), userInfo: nil, repeats: false);
        };
    }
    
    @IBAction func OnclickAction(_ sender: UIBarButtonItem) {
        
        let vc = CfgViewController.getActivity();
        self.present(vc, animated: false, completion: {
            
        });
    }
    // 下拉刷新
    private var refreshTimer:Timer?;
    func pullRefresh(){
        print("结束刷新");
        self.tableView.pullToRefreshView.stopAnimating();
    }
    
    // 初始化广播
    private func reciveBroadcast(){
        let nc = NotificationCenter.default;
        
        nc.addObserver(self, selector:#selector(self.bleEnableChange), name: NSNotification.Name(rawValue: MTBLEManager.ENABLEBLE_CHANGE), object: nil);
    }
    
    // 蓝牙状态改变
    func bleEnableChange(notification:NSNotification){
        let enble = notification.object as! Bool;
        
        if(enble){
            MTTools.logout(log: "开启蓝牙");
            manager.startScan(scanmode: MTBLEManager_ScanMode.FAST, serviceUuids: nil, scanCallback: scanCallback, worktime: 10, sleeptime: 1, scanTimes: 0);
        }else{
            MTTools.logout(log: "关闭蓝牙");
        }
    }
    
    // 初始化蓝牙
    private var manager:MTBLEManager!;
    private var scanCallback:MTBLEManager_ScanCallback!;
    private func initBLE(){
        manager = MTBLEManager.getInstance();
        scanCallback = MTBLEManager_ScanCallback();
        scanCallback.onScan = onScan;
        scanCallback.onScanFail = onScanFail;
        scanCallback.onScanOver = onScanOver;
        if(!manager.isEnable()){
            return;
        }
        
        manager.startScan(scanmode: MTBLEManager_ScanMode.FAST, serviceUuids: nil, scanCallback: scanCallback, worktime: 10, sleeptime: 1, scanTimes: 0);
    }
    
    // 扫描失败
    func onScanFail(erro: ErroCode?){
        
    }
    
    // 扫描完成
    func onScanOver(errocode: ErroCode?){
        
    }
    
    // 扫描结果
    func onScan(device: MTBLEDevice){
        if(!deviceFilter(device: device)){
            return;
        }
        
        var findflag = false;
        for olddevice in mStaticDatas.deviceList{
            if(olddevice.getDevice().identifier == device.getDevice().identifier){
                olddevice.reflashInf(device: device);
                findflag = true;
                break;
            }
        }
        
        if(!findflag){
            mStaticDatas.deviceList.append(device);
        }
        
        self.tableView.reloadData();
    }
    
    // 过滤设备
    private func deviceFilter(device: MTBLEDevice) -> Bool{
        if(mStaticDatas.mixDatas.usertype == 0){  // 智能连接，任何设备都允许通过
            return true;
        }
        
        if(mStaticDatas.mixDatas.usertype == 1){  // 馒头Beacon用户
            if((device.getDevicetype() == MTBLEDevice_MTBLEDEVICETYPE.MTBeacon3) || (device.getDevicetype() == MTBLEDevice_MTBLEDEVICETYPE.MTBeacon4)){
                return true;
            }
            return false;
        }
        
        if(mStaticDatas.mixDatas.usertype == 2){  // 馒头透传模块用户
            if(device.getDevicetype() == MTBLEDevice_MTBLEDEVICETYPE.MTBLE){
                return true;
            }
            return false;
        }
        
        return false;
    }
}
